package com.fjrz.bbxwj.main.video.base

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.view.View
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.PagerSnapHelper
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.SPStaticUtils
import com.blankj.utilcode.util.ToastUtils
import com.module.lemlin.mode.ViewModeFragment
import com.module.lemlin.rxhttp.Status
import com.module.lemlin.rxhttp.msg
import com.shuyu.gsyvideoplayer.GSYVideoManager
import com.shuyu.gsyvideoplayer.player.IjkPlayerManager
import com.shuyu.gsyvideoplayer.player.PlayerFactory
import com.fjrz.bbxwj.R
import com.fjrz.bbxwj.app.WX_APP_ID
import com.fjrz.bbxwj.entity.UserIsFollow
import com.fjrz.bbxwj.entity.VideoIsLike
import com.fjrz.bbxwj.entity.VideoList
import com.fjrz.bbxwj.main.host.side.MainReportActivity
import com.fjrz.bbxwj.main.video.CustomGSYVideoPlayer
import com.fjrz.bbxwj.main.video.VideoAdvertisingActivity
import com.fjrz.bbxwj.main.video.adapter.PlayerGSYAdapter
import com.fjrz.bbxwj.mode.vm.VideoViewModel
import com.fjrz.bbxwj.popup.VideoDiscussPopup
import com.fjrz.bbxwj.popup.VideoSharePopup
import com.fjrz.bbxwj.util.AudioMngHelper
import com.module.lemlin.rxhttp.code
import com.module.lemlin.view.LoadingDialog
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import kotlinx.android.synthetic.main.activity_test_video.*
import kotlinx.android.synthetic.main.popup_video_share.view.*
import java.io.BufferedInputStream
import java.io.InputStream
import java.net.HttpURLConnection
import java.net.URL
import java.net.URLConnection

open class BaseVideoFragment : ViewModeFragment<VideoViewModel>() {

    //视频列表适配器
    val mPlayerAdapter: PlayerGSYAdapter =
        PlayerGSYAdapter()

    //保存当前下标
    var mCurrentPosition: Int = 0

    //分页器助手
    lateinit var mSnapHelper: PagerSnapHelper

    //布局管理器
    lateinit var mLayoutManager: LinearLayoutManager

    //滑动监听器
    val mOnScrollListener: RecyclerView.OnScrollListener by lazy {
        object : RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                if (newState != RecyclerView.SCROLL_STATE_IDLE)
                    return
                val view: View = mSnapHelper.findSnapView(mLayoutManager)
                    ?: return
                val position: Int = recyclerView.getChildLayoutPosition(view)
                if (mCurrentPosition != position) {
                    GSYVideoManager.releaseAllVideos()
                    val gsyVideoPlayer: CustomGSYVideoPlayer =
                        mPlayerAdapter.getCustomGSYVideoPlayer(position)
                            ?: return
                    gsyVideoPlayer.startPlayLogic()
                }
                mCurrentPosition = position
            }
        }
    }

    private val mVideoDiscussPopup: VideoDiscussPopup by lazy {
        VideoDiscussPopup(
            context = requireActivity(),
            onDiscuss = { view, position, commentGroup ->
                if (view.id == R.id.tvDiscussGroupGreat) {
                    if (commentGroup.like == 1) {
                        viewModel.commentUnLike(commentGroup.id, position)
                    } else {
                        viewModel.commentLike(commentGroup.id, position)
                    }
                } else if (view.id == R.id.tvDiscussGroupMore) {
                    viewModel.commentChildList(commentGroup.id, position)
                }
            },
            onDiscussSend = {
                viewModel.commentSubmit(it)
            },
            onLoadMore = {
                viewModel.commentList(it, isLoadMore = true)
            })
    }

    private val mVideoSharePopup: VideoSharePopup by lazy {
        VideoSharePopup(context = requireContext()) { view, videoList ->
            if (view.id == R.id.ivVideoShareReport) {
                videoList?.let {
                    MainReportActivity.open(activity = requireActivity(), videoId = videoList.id)
                    mVideoSharePopup.dismiss()
                }
            } else if (view.id == R.id.ivVideoShareShieldDynamic) {
                videoList?.let {
                    viewModel.userShield(type = 1, targetId = it.id)
                }
            } else if (view.id == R.id.ivVideoShareShieldPeople) {
                videoList?.let {
                    viewModel.userShield(type = 2, targetId = it.user.id)
                }
            } else if (view.id == R.id.ivVideoShareWX2) {
                LogUtils.e("=====ddddd===ddddddd")
                videoList?.let {
                    viewModel.videoShare("1", it.id.toString())
                }
            }
        }
    }


    override val layoutResId: Int
        get() = R.layout.activity_test_video

    override fun viewModel(): VideoViewModel {
        return createViewModel()
    }

    override fun initView() {

        //切换播放器内核
        PlayerFactory.setPlayManager(IjkPlayerManager::class.java)

        mSnapHelper = PagerSnapHelper().apply {
            attachToRecyclerView(rvVideoBody)
        }

        rvVideoBody.apply {
            layoutManager = LinearLayoutManager(
                requireContext(), LinearLayoutManager.VERTICAL, (false)
            ).apply { mLayoutManager = this }
            addOnScrollListener(mOnScrollListener)
        }.adapter = mPlayerAdapter.apply {
            setEmptyView(createViewEmptyLoad())
        }

        mPlayerAdapter.setOnItemChildClickListener { _, view, position ->
            setOnItemChildClickListener(mPlayerAdapter.getItem(position), view, position)
        }

        mSmartRefreshLayout.setOnRefreshListener {
            setOnRefreshListener(it)
        }

        mSmartRefreshLayout.setOnLoadMoreListener {
            setOnLoadMoreListener(it)
        }

        if (this is VideoUserFragment) {
            mSmartRefreshLayout.setEnableRefresh(false)
            mSmartRefreshLayout.setEnableLoadMore(false)
        }
    }


    override fun initViewMode() {
        viewModel.videoListLiveData.observe(viewLifecycleOwner, Observer { response ->

            val isLoadMore: Boolean = response.httpData?.loadMore ?: false

            if (response.status == Status.FAILURE) {
                if (isLoadMore) {
                    mSmartRefreshLayout.finishLoadMore(false)
                } else {
                    mSmartRefreshLayout.finishRefresh(false)
                }
                mPlayerAdapter.setEmptyView(
                    createViewEmptyNull(
                        hint = response.throwable?.msg ?: "未知错误"
                    )
                )
                if (mPlayerAdapter.data.size == 0) {
                    mSmartRefreshLayout.setEnableLoadMore(false)
                }
            }
            if (response.status != Status.SUCCESS)
                return@Observer
            mSmartRefreshLayout.finishRefresh()
            mSmartRefreshLayout.finishLoadMore()

            val videoLists: MutableList<VideoList> =
                response.httpData?.data ?: mutableListOf()

            if (videoLists.isNullOrEmpty() && mPlayerAdapter.data.isNullOrEmpty()) {
                mSmartRefreshLayout.setEnableLoadMore(false)
                mPlayerAdapter.setEmptyView(createViewEmptyNull(hint = "暂无数据"))
            }
            if (isLoadMore) {
                mPlayerAdapter.addData(videoLists)
            } else {
                mPlayerAdapter.setNewInstance(videoLists)
            }

        })

        viewModel.commentGroupLiveData.observe(viewLifecycleOwner, Observer { response ->
            if (response.status != Status.SUCCESS)
                return@Observer
            response.httpData?.let {
                mVideoDiscussPopup.setDiscussData(it)
                mVideoDiscussPopup.showPopupWindow()
            }
        })

        viewModel.commentChildLiveData.observe(viewLifecycleOwner, Observer { response ->
            if (response.status == Status.FAILURE)
                toast(response.throwable?.code, response.throwable?.msg)
            if (response.status != Status.SUCCESS)
                return@Observer
            val position: Int = response.httpData?.position ?: 0
            response.httpData?.data?.data?.let {
                mVideoDiscussPopup.updateDiscussMore(position, it)
            }
        })

        viewModel.commentGreatLiveData.observe(viewLifecycleOwner, Observer { response ->
            if (response.status == Status.FAILURE)
                toast(response.throwable?.code, response.throwable?.msg)
            if (response.status != Status.SUCCESS)
                return@Observer
            response.httpData?.let {
                mVideoDiscussPopup.updateDiscussGreat(it.position, it.isList)
            }
        })

        viewModel.commentSubmitLiveData.observe(viewLifecycleOwner, Observer { response ->
            if (response.status == Status.FAILURE)
                toast(response.throwable?.code, response.throwable?.msg)
            if (response.status != Status.SUCCESS)
                return@Observer
            mVideoDiscussPopup.resetDiscussView()
        })

        viewModel.userShieldLiveData.observe(viewLifecycleOwner, Observer { response ->
            if (response.status == Status.FAILURE) {
                mVideoSharePopup.dismiss()
                toast(response.throwable?.code, response.throwable?.msg)
            }
            if (response.status != Status.SUCCESS)
                return@Observer
            mVideoSharePopup.dismiss()
            toast(message = response.httpData?.msg ?: "屏蔽成功")
        })

        viewModel.videoShareLiveData.observe(viewLifecycleOwner, Observer { response ->
            when (response.status) {
                Status.START -> {
                    mVideoSharePopup.dismiss()
                    LoadingDialog.show(requireContext())
                }
                Status.FAILURE -> {
                    LoadingDialog.dismiss()
                    toast(message = response.throwable?.msg ?: "未知错误")
                }
            }
            if (response.status != Status.SUCCESS)
                return@Observer
            val share = response.httpData?.data
                ?: return@Observer

            Thread {
                val bitmap = getBitmap(share.image)
                requireActivity().runOnUiThread {
                    LoadingDialog.dismiss()
                    shareWeb(
                        context = requireActivity(), appId = WX_APP_ID,
                        webUrl = share.url, title = share.title,
                        content = share.description, bitmap = bitmap
                    )
                }
            }.start()
        })
    }

    fun getBitmap(url: String): Bitmap? {
        var bm: Bitmap? = null
        try {
            val iconUrl = URL(url)
            val conn: URLConnection = iconUrl.openConnection()
            val http: HttpURLConnection = conn as HttpURLConnection
            val length: Int = http.contentLength
            conn.connect()
            // 获得图像的字符流
            val `is`: InputStream = conn.getInputStream()
            val bis = BufferedInputStream(`is`, length)
            bm = BitmapFactory.decodeStream(bis)
            bis.close()
            `is`.close() // 关闭流
        } catch (e: Exception) {
            return null
        }
        return bm
    }

    /**
     * 分享网页类型至微信
     *
     * @param context 上下文
     * @param appId   微信的appId
     * @param webUrl  网页的url
     * @param title   网页标题
     * @param content 网页描述
     * @param bitmap  位图
     */
    fun shareWeb(
        context: Context?,
        appId: String?,
        webUrl: String?,
        title: String?,
        content: String?,
        bitmap: Bitmap?
    ) {
        // 通过appId得到IWXAPI这个对象
        val wxapi = WXAPIFactory.createWXAPI(context, appId)
        // 检查手机或者模拟器是否安装了微信
        if (!wxapi.isWXAppInstalled) {
            toast(message = "手机未安装微信")
            return
        }

        // 初始化一个WXWebpageObject对象
        val webpageObject = WXWebpageObject()
        // 填写网页的url
        webpageObject.webpageUrl = webUrl

        // 用WXWebpageObject对象初始化一个WXMediaMessage对象
        val msg = WXMediaMessage(webpageObject)
        // 填写网页标题、描述、位图
        msg.title = title
        msg.description = content
        // 如果没有位图，可以传null，会显示默认的图片
        msg.setThumbImage(bitmap)

        // 构造一个Req
        val req = SendMessageToWX.Req()
        // transaction用于唯一标识一个请求（可自定义）
        req.transaction = System.currentTimeMillis().toString()
        // 上文的WXMediaMessage对象
        req.message = msg
        // SendMessageToWX.Req.WXSceneSession是分享到好友会话
        // SendMessageToWX.Req.WXSceneTimeline是分享到朋友圈
        req.scene = SendMessageToWX.Req.WXSceneSession

        // 向微信发送请求
        wxapi.sendReq(req)
    }

    override fun onStop() {
        super.onStop()
        mPlayerAdapter.getCustomGSYVideoPlayer(mCurrentPosition)
            ?.onVideoPause()
    }

    override fun onPause() {
        super.onPause()
        if (GSYVideoManager.instance().isPlaying) {
            GSYVideoManager.instance().stop()
        }
    }

    override fun onRefreshLoad() {
        super.onRefreshLoad()
        mPlayerAdapter.getCustomGSYVideoPlayer(mCurrentPosition)
            ?.startPlayLogic()
    }

    override fun onDestroy() {
        super.onDestroy()
        GSYVideoManager.releaseAllVideos()
    }

    override fun onEventMainThread(any: Any) {
        val position: MutableList<Int> = mutableListOf()
        val videoLists: MutableList<VideoList> = mPlayerAdapter.data
        if (any is UserIsFollow)
            for ((index: Int, videoList: VideoList) in videoLists.withIndex()) {
                if (videoList.user_id == any.user_id) {
                    videoList.apply { followed = any.isFollow }
                    position.add(index)
                }
            }
        else if (any is VideoIsLike)
            for ((index: Int, videoList: VideoList) in videoLists.withIndex()) {
                if (videoList.id == any.video_id) {
                    videoList.apply {
                        like = any.isLike
                        likes = any.like_count
                    }
                    position.add(index)
                }
            }
        position.forEach {
            val mCustomGSYVideoPlayer: CustomGSYVideoPlayer? =
                mPlayerAdapter.getCustomGSYVideoPlayer(it)
            if (mCustomGSYVideoPlayer != null) {
                mCustomGSYVideoPlayer.setVideoList(videoLists[it])
            } else {
                mPlayerAdapter.setData(it, videoLists[it])
            }
        }
    }

    open fun setOnItemChildClickListener(
        videoList: VideoList, view: View, position: Int
    ) {
        if (view.id == R.id.ivControlsAttention) {
            viewModel.userFollow(videoList.user_id)
        } else if (view.id == R.id.tvControlsApprove && videoList.like == 0) {
            viewModel.videoLike(videoList.id)
        } else if (view.id == R.id.tvControlsApprove && videoList.like == 1) {
            viewModel.videoUnLike(videoList.id)
        } else if (view.id == R.id.tvControlsDiscuss) {
            mVideoDiscussPopup.initDiscussView(videoList.id)
            viewModel.commentList(videoList.id)
        } else if (view.id == R.id.tvControlsShare) {
            mVideoSharePopup.setVideoId(videoList)
                .showPopupWindow()
        } else if (view.id == R.id.tvControlsAdDetails) {
            VideoAdvertisingActivity.open(
                activity = requireActivity(),
                videoId = videoList.id,
                adImage = videoList.adv_image,
                adTitle = videoList.adv_title
            )
        }
    }

    open fun setOnRefreshListener(refreshLayout: RefreshLayout) = Unit

    open fun setOnLoadMoreListener(refreshLayout: RefreshLayout) = Unit
}